package cn.xyinping.basic.interceptor;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;

/**
 * @author 27266
 * @desrciption 登陆拦截器
 * @date 2021/10/30
 */
@Component  // 交给spring管理
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        // token
        String token = request.getHeader("token");
        // 从redis中取数据
        if(!StringUtils.isEmpty(token)){  //不为空
            Object obj = redisTemplate.opsForValue().get(token);
            if(obj!=null){   //  没有过期
                // 刷新redis过期时间
                redisTemplate.opsForValue().set(
                        token,
                        obj,
                        30,
                        TimeUnit.MINUTES);
                // 放行
                return true;
            }
        }
        //  过期了。   {"success": false, "msg": "nologin"}
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json; charset=UTF-8");
        PrintWriter writer = response.getWriter();
        // 在外面写好在拷贝进去
        writer.write("{\"success\":false,\"message\":\"noLogin\"}");
        writer.close();
        return false;
    }
}
